package com.ly.common.utils;

import com.ly.common.models.common.DataMap;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * @Auther: lzw
 * @Date: 2018/6/4
 */
public class StringUtil {

    /**
     * map转为String
     * @param map
     * @return
     */
    public static String mapToString(Map<String, String> map) {
        if (map == null) {
            return null;
        }
        StringBuffer sbResult = new StringBuffer();
        for (String key : map.keySet()) {
            sbResult.append(key + "=" + map.get(key) + "&");
        }
        String result = sbResult.toString();
        if (result.length() > 0) {
            result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 批量替换字符串中的字符
     *
     * @param str
     * @param map
     * @return
     */
    public static String replaceStr(String str, Map<String, String> map) {
        if (str == null || "".equals(str)) {
            return str;
        }
        for (String key : map.keySet()) {
            str = str.replaceAll(key, map.get(key));
        }
        return str;
    }

    /**
     * 异常信息转为字符串
     * @param e
     * @return
     */
    public static String errorToString(Throwable e) {
        StringBuffer sb = new StringBuffer();
        StackTraceElement[] stackArray = e.getStackTrace();
        for (int i = 0; i < stackArray.length; i++) {
            StackTraceElement element = stackArray[i];
            sb.append(element.toString() + "\n");
        }
        return sb.toString();
    }

    /**
     * 判断传入参数,如果是Null或者空值，返回false，不为空返回true
     * @param checkAll
     * True:所有的为空才返回,False:只要有一个为空返回
     * @return
     */
    public static Boolean checkNull(Boolean checkAll, Object... objects) {
        Boolean ret = true;
        if (objects == null)
            return false;
        for (Object s : objects) {
            if (null == s || ("").equals(s.toString().trim())) {
                if (!checkAll)
                    return false;
                else {
                    ret = false;
                }
            }
        }
        return ret;
    }

    /**
     * json转map （自定义Map）
     * @param json
     * @return
     */
    public static DataMap<String,Object> jsonStrToMap(String json){
        DataMap<String, Object> dataMap=new DataMap<String,Object>();
        try{
            ObjectMapper objMapper = new ObjectMapper();
            dataMap = objMapper.readValue(json, DataMap.class);
        }catch (Exception e){
           dataMap=null;
        }
        return dataMap;
    }
    
    /**
	 * 手机号码验证 
	 */
	public static boolean CheckPhoneNumber(String paramString) {
		if (Pattern.matches("^[1][3,4,5,7,8][0-9]{9}$", paramString)) {                 
			return true;    
		} else {
			return false;
		}
	}

    /**
     * 字符串排序(中文按拼音排)
     * @param s
     * @return
     */
    public static String strSort(String s) {
        if(s==null){
            return s;
        }
        String charset="gb2312";
        char[] c = s.toCharArray();
        for (int i = 0; i < c.length - 1; i++) {
            for (int j = i + 1; j < c.length; j++) {
                if (getHexString(new String(new char[] { c[i] }), charset)
                        .compareTo(
                                getHexString(new String(new char[] { c[j] }),
                                        charset)) > 0) {
                    char temp = c[i];
                    c[i] = c[j];
                    c[j] = temp;
                }
            }

        }
        return new String(c);
    }

    private static String getHexString(String s, String charset) {
        byte[] b = null;
        StringBuffer sb = new StringBuffer();
        try {
            b = s.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < b.length; i++) {
            sb.append(Integer.toHexString(b[i] & 0xFF));
        }
        return sb.toString();
    }

 public static Boolean isEmpty(String str){
    if(str==null || str.length()==0)
        return true;
     else
        return false;
 }


    /**
     * ascii排序
     * @param str
     * @return
     */
    public static String sort(String str)
    {
        if(str==null || "".equals(str)){
            return str;
        }
        char[] ch = str.toCharArray();
        Arrays.sort(ch);
        return new String(ch);
    }


    /**
     * 判断字符串编码
     * @param str
     * @return
     */
    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }

    public static void main(String[] args) throws Exception{
        String str=new String("阿萨德".getBytes("utf-8"),"gbk");
        str="{\"contact\":\"å\u0095¦å\u0095¦å\u0095¦\",\"phone\":\"13536363658\",\"province\":\"æ²³å\u008C\u0097ç\u009C\u0081\",\"city\":\"ç§¦ç\u009A\u0087å²\u009Bå¸\u0082\",\"area\":\"å\u008C\u0097æ\u0088´æ²³å\u008Cº\",\"street\":\"\",\"address\":\"è\u0080\u0083è\u0099\u0091è\u0080\u0083è\u0099\u0091\",\"zipCode\":\"\"}";
        System.out.println(getEncoding(str));
    }

}
